import route, { defalutRoutes } from '@/router';
import getUserInfo from './getUserInfo';
import request from "../request/index";
import setRouter from '../router/setRouter';
import setting from '@/setting';
import { setCookie } from "./cookie";

/**白名单routerList*/
const whiteList = ['/login', '/401', '/403', '/404' , '/auth-redirect'];

route.beforeEach((to, from, next) => {
    if (to.meta.title) {
        document.title = to.meta.title + '-' + setting.title;
    } else {
        document.title = setting.title;
    }
    if (whiteList.indexOf(to.path) !== -1) {
        next();
        return;
    }
    if (!getUserInfo()) {
        const redirect = encodeURIComponent(to.fullPath)
        window.location.href = `/login.html?redirect=${redirect}`;
        return;
    }
    next();
})

/**获取用户权限和菜单路由*/
const getUserInfoByAdmin = (stores: any) => {
    return request({
        url: "/api/v2/users/getUserInfoByAdmin",
        method: "post",
        success(res) {
            setCookie('userInfo' , JSON.stringify(res.data.userInfo))
            if (!res.data.data.menu.length) {
                let indexRouter = [{path: '/',redirect: '/401',name: 'Index',}]
                setRouter(indexRouter);
                stores.useMenuStore().setMenu([...indexRouter, ...defalutRoutes]);
                route.push('/401');
                return;
            }
            let fullPath = route.currentRoute.value.fullPath;
            let path = route.currentRoute.value.path;
            let menus: Array<any> = [];
            res.data.data.menu.forEach((item: any) => {
                menus.push(item);
                menus.push(...item.children);
            });
            let hasPath = menus.some((item: any) => item.path == path);
            if (!hasPath) {
                fullPath = res.data.data.menu[0].children && res.data.data.menu[0].children.length ? res.data.data.menu[0].children[0].path : res.data.data.menu[0].path;
                if (res.data.data.menu[0].children && res.data.data.menu[0].children.length) {
                    res.data.data.menu[0].path = '/';
                    res.data.data.menu[0].redirect = fullPath;
                } else {
                    res.data.data.menu[0].path = '/';
                    fullPath = res.data.data.menu[0].path;
                }
            }
            setRouter(res.data.data.menu);
            stores.useMenuStore().setMenu([...defalutRoutes, ...res.data.data.menu]);
            if (whiteList.indexOf(path) !== -1) {
                return;
            }
            route.push(fullPath)
        }
    })
}

export default {
    getUserInfoByAdmin
}

